package com.jack.blog.service.serviceImpl;

import com.jack.blog.dao.CategoryMapper;
import com.jack.blog.dao.BlogMapper;
import com.jack.blog.dto.CategoryDto;
import com.jack.blog.entity.Blog;
import com.jack.blog.entity.Category;
import com.jack.blog.service.CategoryService;
import com.jack.blog.vo.CategoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private CategoryDto categoryDto;

    @Override
    public List<CategoryVo> getCategories(int uid) throws Exception {
        List<Category> categories = categoryMapper.queryBlogCategories(uid);
        return categoryDto.CategoryToCategoryVo(categories);
    }

    @Override
    public CategoryVo getCategory(int cid) throws Exception {
        Category category = categoryMapper.queryBlogCategory(cid);
        return categoryDto.CategoryToCategoryVo(category);
    }

    @Override
    public void addCategory(int uid, CategoryVo categoryVo) {
        Category category = categoryDto.CategoryVoToCategory(uid, categoryVo);
        categoryMapper.insertBlogCategory(category);
    }

    @Override
    public void updateCategory(int id,int uid,CategoryVo categoryVo) throws IllegalArgumentException {
        Category category = categoryDto.CategoryVoToCategory(id,categoryVo);
        int defaultCid = categoryMapper.queryDefaultCid(uid);
        if (category.getId()==defaultCid)
            throw new IllegalArgumentException("cant delete default category!");
        categoryMapper.updateBlogCategory(id,category.getValue(),category.getIntroduction(),0);
    }

    @Override
    @Transactional
    public int deleteCategory(int uid, int cid) {
        int defaultCid = categoryMapper.queryDefaultCid(uid);
        if (cid==defaultCid)
            throw new IllegalArgumentException("cant delete default category!");
        List<Blog> blogs = blogMapper.queryBlogsByCid(cid,0,Integer.MAX_VALUE);
        for (Blog blog:blogs) {
            blogMapper.updateBlogInfo(blog.getId(), null, null, defaultCid, null, null);
            categoryMapper.updateBlogCategory(defaultCid, null, null, 1);
        }
        categoryMapper.deleteBlogCategory(cid);
        return defaultCid;
    }


}
